package Dao.Impl;

import Dao.AdminDAO;
import MyUtil.JDBCUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class AdminDAOImpl implements AdminDAO {

    //构造方法
    public AdminDAOImpl() throws Exception {
    }

    //判断登录，成功 id，失败 -1
    @Override
    public int administratorLogin(String username, String password) throws Exception {
        //获取连接
        Connection adminDAOImplConn = JDBCUtils.getMyConnection();
        String sql;
        PreparedStatement ps;
        ResultSet rs;
        //查询SQL
        sql = "select * from admin where username =? and password = ?";
        ps = adminDAOImplConn.prepareStatement(sql);
        //占位符的赋值
        ps.setString(1,username);
        ps.setString(2,password);
        rs = ps.executeQuery();
        //判断结果
        if(rs.next()){
            return rs.getInt("admin_id");
        }
//        关闭资源
         JDBCUtils.release(adminDAOImplConn,ps,rs);
        return -1;
    }

    //注册管理员,成功true，失败false
    @Override
    public boolean administratorRegister(String username, String password) throws Exception {
        //获取连接
        Connection adminDAOImplConn = JDBCUtils.getMyConnection();
        String sql;
        PreparedStatement ps;
        ResultSet rs;
        //增加sql语句
        sql = "insert into admin(username,password) values(?,?)";
        ps = adminDAOImplConn.prepareStatement(sql);
        ps.setString(1,username);
        ps.setString(2,password);
        int count = ps.executeUpdate();
        if (count!=0){
            return true;
        }
        return false;
    }

    //判断管理员用户名是否存在
    @Override
    public boolean checkAdminNameExist(String username) throws Exception {
        //获取连接
        Connection adminDAOImplConn = JDBCUtils.getMyConnection();
        String sql;
        PreparedStatement ps;
        ResultSet rs;
        //查询SQL
        sql = "select * from admin where username = ?";
        ps = adminDAOImplConn.prepareStatement(sql);
        ps.setString(1,username);
        rs = ps.executeQuery();
        if (rs.next()){
            return true;
        }
        return false;
    }
}
